﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SGArchiveSystem7xDB.Linq
{
    /// <summary>
    /// 档案树
    /// </summary>
    public class T_ArchiveTreeDal
    {
        static SGArchiveSystem7xEntities conn;
        /// <summary>
        /// 添加档案树
        /// </summary>
        /// <param name="en"></param>
        /// <returns></returns>
        public static _ReturnValue Add_ArchiveTree(T_ArchiveTree en)
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                if (conn.T_ArchiveTree.Select(c => c).Where(c => c.AR_NAME == en.AR_NAME).Count() > 0)
                    return _ReturnValue.Already;
                else
                {
                    conn.T_ArchiveTree.Add(en);
                    conn.SaveChanges();

                    return _ReturnValue.OK;
                }
            }
            catch { return _ReturnValue.Already; }
        }

        /// <summary>
        /// 获取档案树, 获取档案树不需要使用分页
        /// </summary>
        /// <returns></returns>
        public static List<T_ArchiveTree> Get_ArchiveTree(int pid=-1, int status=-1)
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                var query = conn.T_ArchiveTree.Select(c => c);
                if (pid > -1)
                    query = query.Where(c => c.AR_PID == pid);
                if (status > -1)
                    query = query.Where(c => c.AR_STATUS == status);
                return query.OrderBy(c => c.AR_PID).ThenBy(c => c.AR_ID).ToList();
            }
            catch { return null; }
        }
        public static T_ArchiveTree Get_SingleTree(int id)
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                return conn.T_ArchiveTree.Select(c => c).Where(c => c.AR_ID == id).Single();
            }
            catch { return null; }
        }


        public static _ReturnValue Modify_ArchiveTree(int id, string name)
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                if (conn.T_ArchiveTree.Select(c => c).Where(c => c.AR_ID != id && c.AR_NAME == name).Count() > 0)
                    return _ReturnValue.Already;
                var query = conn.T_ArchiveTree.Select(c => c).Where(c => c.AR_ID == id);
                foreach (var n in query)
                    n.AR_NAME = name;
                conn.SaveChanges();
                return _ReturnValue.OK;
            }
            catch { return _ReturnValue.Err; }
        }
    }
}
